package com.bsoft.project.base;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.management.ServiceNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 褚国强
 * @Date: 2020/07/13/17:28
 * @Description:
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,Exception ex){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("errMsg",ex.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;

    }

    /**
     * 处理参数异常，一般用于校验body参数
     * @param e
     * @return
     */
    @ExceptionHandler(ServletException.class)
    public SystemException handleValidationBodyException(MethodArgumentNotValidException e) {
        for (ObjectError s : e.getBindingResult().getAllErrors()) {
            return new SystemException("Invalid_Request_Parameter", s.getObjectName() + ": " + s.getDefaultMessage());
        }
        return new SystemException("Invalid_Request_Parameter", "未知参数错误");
    }

    /**
     * 主动throw的异常
     *
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(ServiceNotFoundException.class)
    public SystemException handleUnProccessableServiceException(ServiceNotFoundException e, HttpServletResponse response) {
        response.setStatus(4023); //4023自己定义
        return new SystemException(e.getMessage());
    }

}
